import numpy as np
from scipy.optimize import leastsq
'''
    求形如y=a+bx^2 的经验公式
'''
x=np.array([19,25,31,38,44])
y=np.array([19.0,32.3,49.0,73.3,97.8])
func=lambda ab,x:ab[0]+ab[1]*x*x
error=lambda ab,x,y:func(ab,x)-y
# 得到拟合结果a b
res=leastsq(error,[20,20],args=(x,y))
print(res)

'''
    多项式拟合 设y=a1x+a0
'''
year=np.array([1990,1991,1992,1993,1994,1995,1996])
money=np.array([70,122,144,159,174,196,202])
# 一次多项式
z=np.polyfit(year,money,1)
# 生成多项式
p1=np.poly1d(z)
print(p1)

'''
    拟合复杂函数
'''
y=np.array([15.02,12.62,14.86,13.98,15.91,12.47,15.80,14.32,13.76,15.18,14.20,17.07,15.40,15.94,14.33,15.11,13.81,15.58,15.85,15.28,16.40,15.02,15.73,14.75,14.35])
x1=np.array([23.73,22.34,28.84,27.67,20.83,22.27,27.57,28.01,24.79,28.96,25.77,23.17,28.57,23.52,21.86,28.95,24.53,27.65,27.29,29.07,32.47,29.65,22.11,22.43,20.04])
x2=np.array([5.49,4.32,5.04,4.72,5.35,4.27,5.25,4.62,4.42,5.30,4.87,5.80,5.22,5.18,4.86,5.18,4.88,5.02,5.55,5.26,5.18,5.08,4.90,4.65,5.08])
x3=np.array([1.21,1.35,1.92,1.49,1.56,1.50,1.85,1.51,1.46,1.66,1.64,1.90,1.66,1.98,1.59,1.37,1.39,1.66,1.70,1.82,1.75,1.70,1.71,1.72,1.53])

fune=lambda k,x1,x2,x3:np.e**(-k[0]*x1)*np.sin(k[1]*x2)+x3**2
err=lambda k,x1,x2,x3,y:fune(k,x1,x2,x3)-y
res=leastsq(err,[0,0],args=(x1,x2,x3,y))
print(res[0])
print(err(res[0],x1,x2,x3,y))